package com.ruoyi.api.kehu;

import cn.hutool.core.util.ObjectUtil;
import com.beust.jcommander.internal.Maps;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.ApiTableDataInfo;
import com.ruoyi.common.json.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import com.ruoyi.system.utils.OrderUtil;
import com.ruoyi.system.utils.ProfileUtil;
import com.ruoyi.system.utils.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/api/kehu/jishi")
@Api(tags = "用户端社工相关接口")
public class ApiJiShiController extends BaseController {

    @Autowired
    private IJiajiaUserService userService;

    @Autowired
    private IJiajiaWorkerService workerService;

    @Autowired
    private IJiajiaWorkerItemService workerItemService;
    @Autowired
    private IJiajiaWorkerInterestService jiajiaWorkerInterestService;
    @Autowired
    private IJiajiaItemService itemService;

    @Autowired
    private IJiajiaWorkerPhotoService workerPhotoService;

    @Autowired
    private IJiajiaAppraiseService appraiseService;

    @Autowired
    private IJiajiaOrderService orderService;

    @Autowired
    private IJiajiaOrderTimeService orderTimeService;

    @Autowired
    private IJiajiaUserLikeService userLikeService;

    @Autowired
    private IJiajiaWorkerJiedanService jiedanService;

    @Autowired
    private IJiajiaWorkerJiedanDetailService jiedanDetailService;

    @Autowired
    private IJiajiaWorkerTimeXxConfigService timeXxConfigService;

    @Autowired
    private IJiajiaWorkerTimeConfigService timeConfigService;

    @ApiOperation("社工列表")
    @PostMapping("/jiShiList")
    public ApiTableDataInfo jiShiList(@RequestParam(required = false)@ApiParam(value = "区域id") Integer cityId,
                                      @RequestParam(required = false)@ApiParam(value = "距离") Integer fanWei,
                                      @RequestParam(required = false)@ApiParam(value = "时间段Id") String tcIds,
                                      @RequestParam(required = false)@ApiParam(value = "项目id") Long iid,
                                      @RequestParam(required = false)@ApiParam(value = "社工名称（模糊搜索）")String name,
                                      @RequestParam(required = false)@ApiParam(value = "大类id") Long bigId)
    {


        String widsArr="";
        if (iid != null){
            JiajiaWorkerItem workerItem = new JiajiaWorkerItem();
            workerItem.setIid(iid);
            List<JiajiaWorkerItem> workerItemList = workerItemService.selectJiajiaWorkerItemList(workerItem);

            List<JiajiaWorkerItem> tempWIList = workerItemList.stream().filter(rowVal -> rowVal.getStatus().intValue() == 1).collect(Collectors.toList());
            widsArr = StringUtils.listsToSbStr(tempWIList,"wid");
        }

        JiajiaWorker worker = new JiajiaWorker();
        if (cityId != null && cityId.intValue() != 0){
            worker.setCityId(cityId);
        }
        if (bigId!=null){
            List<JiajiaWorkerItem> workerItemList = workerItemService.selectWorkerItemList(bigId);
            List<JiajiaWorkerItem> tempWIList = workerItemList.stream().filter(rowVal -> rowVal.getStatus().intValue() == 1).collect(Collectors.toList());
            widsArr = StringUtils.listsToSbStr(tempWIList,"wid");
        }
        if (iid != null|| bigId!=null){
            worker.getParams().put("idsArr",widsArr.split(","));
        }
//        if (StringUtils.isNotEmpty(times)){
//            //传时间 如01:00 则今天返回01:00能约的人
//            worker.getParams().put("canYueTime",times.split(","));
//        }

        worker.setCodeAuth(1);
        worker.setName(name);
//        worker.setStatus(1);//服务状态的
        startPage();
        List<JiajiaWorker> workerList = workerService.selectWorkerList(worker);
        List<JiajiaWorker> sortedFruits = workerList.stream()
                .sorted(Comparator
                        .comparing(s -> !s.getStatus().equals(1))  // apple的优先级最高（false在前）
                )
                .collect(Collectors.toList());
        for (JiajiaWorker model:sortedFruits) {
            Long commentsNumber =appraiseService.selectNumber(model.getId());
            model.setCommentsNumber(commentsNumber);
            JiajiaOrder order=orderService.selectorderList(model.getId());
            if (ObjectUtil.isNotNull(order)){
                model.setStatus(0);
            }
            Long likeNum =userLikeService.selectQuantity(model.getId());
            if (likeNum==null){
                model.setQuantity(0L);
            }else {
                model.setQuantity(likeNum);
            }
        }
        List<JiajiaWorker> resList = new ArrayList<>();

        String wids = StringUtils.listsToSbStr(sortedFruits,"id");

        JiajiaOrder order = new JiajiaOrder();
        order.getParams().put("yuYueTime", DateUtils.dateTime(new Date()));
        order.getParams().put("widsArr",wids.split(","));
        order.getParams().put("type","1");
        List<JiajiaOrder> orderList = orderService.selectJiajiaOrderList(order);

        Map<String,List<JiajiaOrder>> orderMap = new HashMap<>();

        for (JiajiaOrder model : orderList) {
            if (!orderMap.containsKey(model.getWid().toString())){
                orderMap.put(model.getWid().toString(),new ArrayList<>());
            }
            orderMap.get(model.getWid().toString()).add(model);
        }

        JiajiaWorkerJiedan jiedan = new JiajiaWorkerJiedan();
        String[] wIds = wids.split(",");
        if(wIds == null || wIds.length <= 0){
            jiedan.getParams().put("widsArr", null);
        }else{
            jiedan.getParams().put("widsArr", wIds);
        }

        jiedan.getParams().put("time",DateUtils.dateTime(new Date()));
        List<JiajiaWorkerJiedan> jiedanList = jiedanService.selectJiajiaWorkerJiedanList(jiedan);
        Map<String,List<JiajiaWorkerJiedan>> jieDanMap = new HashMap<>();
        for (JiajiaWorkerJiedan model : jiedanList) {
            if (!jieDanMap.containsKey(model.getWid().toString())){
                jieDanMap.put(model.getWid().toString(),new ArrayList<>());
            }
            jieDanMap.get(model.getWid().toString()).add(model);
        }

        JiajiaWorkerJiedanDetail detail = new JiajiaWorkerJiedanDetail();
        detail.getParams().put("widIdsArr",wids.split(","));
        String[] jdIds = StringUtils.listsToSbStr(jiedanList,"id").split(",");
        if(jdIds == null || jdIds.length <= 0){
            detail.getParams().put("jdIdsArr", null);
        }else{
            detail.getParams().put("jdIdsArr", jdIds);
        }

        List<JiajiaWorkerJiedanDetail> detailList = jiedanDetailService.selectJiajiaWorkerJiedanDetailList(detail);
        Map<String,List<JiajiaWorkerJiedanDetail>> detailMap = new HashMap<>();
        for (JiajiaWorkerJiedanDetail model :detailList) {
            if (!detailMap.containsKey(model.getWid().toString())){
                detailMap.put(model.getWid().toString(),new ArrayList<>());
            }
            detailMap.get(model.getWid().toString()).add(model);
        }

        JiajiaWorkerTimeConfig jiajiaWorkerTimeConfig = new JiajiaWorkerTimeConfig();
        List<JiajiaWorkerTimeConfig> timeConfigList = timeConfigService.selectJiajiaWorkerTimeConfigList(jiajiaWorkerTimeConfig);

        //计算距离
        for (JiajiaWorker model : sortedFruits) {
            JiajiaWorkerTimeXxConfig timeXxConfig = new JiajiaWorkerTimeXxConfig();
            timeXxConfig.setWid(model.getId());
            timeXxConfig.setDay(DateUtils.getDate());
            timeXxConfig.setStatus(0);
            List<JiajiaWorkerTimeXxConfig> timeXxConfigList = timeXxConfigService.selectTimeXxConfigList(timeXxConfig);
            Set<Long> timeXxConfigSet = timeXxConfigList.stream().map(rowVal -> rowVal.getTcid()).collect(Collectors.toSet());
            long xxCount = timeConfigList.stream().filter(rowVal -> !timeXxConfigSet.contains(rowVal.getId())).count();
            if (xxCount <= 0){//当前所有班全部休息状态
                continue;
            }
            //计算社工的接单位置和用户当前定位位置距离范围
            int juLi = TokenUtil.getLuLiNum(model.getLat(), model.getLng()).intValue();
            model.getParams().put("juLi", juLi);
            if (fanWei != null && fanWei < 999){//999不限距离
                if (juLi > fanWei.floatValue()){
                    continue;
                }
            }
            //距离大于社工接单范围
            if (!ProfileUtil.getActiveProfile().equals(ProfileUtil.PROFILE_DEV)
                    && model.getScope() < 999){//999不限接单范围
                if (juLi > model.getScope()){//非测试环境验证是否超出了接单范围
                    continue;
                }
            }

            boolean isHaveTime = false;
            if (StringUtils.isNotEmpty(tcIds)){//过滤此时段没有时间的社工
                JiajiaOrderTime orderTime = new JiajiaOrderTime();
                Map<String, Object> params = Maps.newHashMap();
                params.put("tcIds", tcIds);
                params.put("status", "3,4,5");
                orderTime.setParams(params);
                orderTime.setWid(model.getId());
                List<JiajiaOrderTime> orderTimeList = orderTimeService.selectJiajiaOrderTimeList(orderTime);
                if(ObjectUtil.isEmpty(orderTimeList)){
                    isHaveTime = true;
                }
//                List<OrderTime> orderTimeList = OrderUtil.getCanYueList(model,
//                        orderMap.get(model.getId().toString()),
//                        jieDanMap.get(model.getId().toString()),
//                        detailMap.get(model.getId().toString()));

//                for (OrderTime time : orderTimeList) {
//                    if (!time.date.equals(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,new Date()))){
//                        continue;
//                    }
//                    if (!time.isUse)continue;
//                    for (String timeStr : times.split(",")) {
//                        if (StringUtils.isEmpty(timeStr))continue;
//                        int a = Integer.valueOf(timeStr.split(":")[0]);
//                        if (a == time.hour){
//                            isHaveTime = true;
//                            break;
//                        }
//                    }
//                }
            }
            if (!isHaveTime && StringUtils.isNotEmpty(tcIds)){
                continue;
            }
            resList.add(model);
        }

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int currentHour = calendar.get(calendar.HOUR_OF_DAY);

        for (JiajiaWorker model : resList) {
            model.getParams().put("zuiZao", OrderUtil.getZuiZao(model,
                    orderMap.get(model.getId().toString()),
                    jieDanMap.get(model.getId().toString()),
                    detailMap.get(model.getId().toString())
            ));



            //关注数

            JiajiaWorkerInterest jiajiaWorkerInterest=new JiajiaWorkerInterest();
            jiajiaWorkerInterest.setWorkerId(model.getId());
            List<JiajiaWorkerInterest> jiajiaWorkerInterests = jiajiaWorkerInterestService.selectJiajiaWorkerInterestList(jiajiaWorkerInterest);
            model.setInterestCount(jiajiaWorkerInterests.size());
            //是否关注
            jiajiaWorkerInterest.setUserId(TokenUtil.getUid());
            List<JiajiaWorkerInterest> jiajiaWorkerInteres = jiajiaWorkerInterestService.selectJiajiaWorkerInterestList(jiajiaWorkerInterest);
            if(Optional.ofNullable(jiajiaWorkerInteres).isPresent()&&jiajiaWorkerInteres.size()>0){
                model.setInterest(1);
            }else{
                model.setInterest(0);
            }
            //点赞
            model.setIsLike(1);
            //是否关注
            JiajiaUserLike userLike = new JiajiaUserLike();
            userLike.setWid(model.getId());
            userLike.setUid(TokenUtil.getUid());
            List<JiajiaUserLike> userLikeList = userLikeService.selectJiajiaUserLikeList(userLike);
            if (userLikeList.isEmpty()){
                model.setIsLike(0);
                model.setFans(0);

            }else{
                model.setFans(userLikeList.size());

            }



//            int star = Integer.valueOf(model.getStarTime().split(":")[0]).intValue();
//            int end = Integer.valueOf(model.getEndTime().split(":")[0]).intValue();
//            //社工状态 上班时间即为可服务
//            model.setStatus(0);
//            if (star <= currentHour && currentHour < end){
//                model.setStatus(1);
//            }
            JiajiaWorkerTimeXxConfig timeXxConfig = new JiajiaWorkerTimeXxConfig();
            timeXxConfig.setWid(model.getId());
            timeXxConfig.setDay(DateUtils.getDate());
            List<JiajiaWorkerTimeXxConfig> timeXxConfigList = timeXxConfigService.selectTimeXxConfigList(timeXxConfig);
            if (ObjectUtil.isNotEmpty(timeXxConfigList)){
                for (JiajiaWorkerTimeXxConfig config : timeXxConfigList) {
                    int star = Integer.valueOf(config.getStartime().split(":")[0]).intValue();
                    int end = Integer.valueOf(config.getEndtime().split(":")[0]).intValue();
                    if (star <= currentHour && currentHour < end){
                        if (config.getStatus() == 0&&star <= currentHour && currentHour < end){
                            model.setStatus(0);
                        }
                        model.setStatus(1);
                    }
                }
            }

        }
        return getApiDataTable(resList);
    }

    @ApiOperation("社工详情")
    @PostMapping("/detail")
    public AjaxResult detail(@RequestParam @ApiParam(value = "社工id") Long wid)
    {
        JiajiaWorker worker = workerService.selectJiajiaWorkerById(wid);

        //关注数

        JiajiaWorkerInterest jiajiaWorkerInterest=new JiajiaWorkerInterest();
        jiajiaWorkerInterest.setWorkerId(worker.getId());
        List<JiajiaWorkerInterest> jiajiaWorkerInterests = jiajiaWorkerInterestService.selectJiajiaWorkerInterestList(jiajiaWorkerInterest);
        worker.setInterestCount(jiajiaWorkerInterests.size());
        //是否关注
        jiajiaWorkerInterest.setUserId(TokenUtil.getUid());
        List<JiajiaWorkerInterest> jiajiaWorkerInteres = jiajiaWorkerInterestService.selectJiajiaWorkerInterestList(jiajiaWorkerInterest);
        if(Optional.ofNullable(jiajiaWorkerInteres).isPresent()&&jiajiaWorkerInteres.size()>0){
            worker.setInterest(1);
        }else{
            worker.setInterest(0);
        }

        if (worker == null)return AjaxResult.refreshAgain();

        //社工照片
        JiajiaWorkerPhoto workerPhoto = new JiajiaWorkerPhoto();
        workerPhoto.setWid(worker.getId());
        workerPhoto.setDel(0l);
        PageHelper.startPage(1,4,"addtime desc");
        List<JiajiaWorkerPhoto> workerPhotoList = workerPhotoService.selectJiajiaWorkerPhotoList(workerPhoto);

        //社工评价
        JiajiaAppraise appraise = new JiajiaAppraise();
        appraise.setWid(worker.getId());
        appraise.setDel(0l);
        PageHelper.startPage(1,3,"addtime desc");
        List<JiajiaAppraise> appraiseList = appraiseService.selectJiajiaAppraiseList(appraise);

        //查询社工能提供的项目
        JiajiaWorkerItem workerItem = new JiajiaWorkerItem();
        workerItem.setWid(worker.getId());
        workerItem.setStatus(1);
        List<JiajiaWorkerItem> workerItemList = workerItemService.selectJiajiaWorkerItemList(workerItem);

        String iids = StringUtils.listsToSbStr(workerItemList,"iid");

        JiajiaItem item = new JiajiaItem();
        item.getParams().put("idsArr",iids.split(","));
        item.setIsShow(1);
        List<JiajiaItem> itemList = itemService.selectJiajiaItemList(item);

        JiajiaOrder order = new JiajiaOrder();
        order.getParams().put("yuYueTime", DateUtils.dateTime(new Date()));
        order.getParams().put("type","1");
        order.setWid(worker.getId());
        List<JiajiaOrder> orderList = orderService.selectJiajiaOrderList(order);

        JiajiaWorkerJiedan jiedan = new JiajiaWorkerJiedan();
        jiedan.setWid(worker.getId());
        jiedan.getParams().put("time",DateUtils.dateTime(new Date()));
        List<JiajiaWorkerJiedan> jiedanList = jiedanService.selectJiajiaWorkerJiedanList(jiedan);

        JiajiaWorkerJiedanDetail detail = new JiajiaWorkerJiedanDetail();
        detail.setWid(worker.getId());
        detail.getParams().put("jdIdsArr",StringUtils.listsToSbStr(jiedanList,"id").split(","));
        List<JiajiaWorkerJiedanDetail> detailList = jiedanDetailService.selectJiajiaWorkerJiedanDetailList(detail);

        JSONObject resObj = new JSONObject();
        resObj.put("isLike",1);
        //是否关注
        JiajiaUserLike userLike = new JiajiaUserLike();
        userLike.setWid(wid);
        userLike.setUid(TokenUtil.getUid());
        List<JiajiaUserLike> userLikeList = userLikeService.selectJiajiaUserLikeList(userLike);
        if (userLikeList.isEmpty()){
            resObj.put("isLike",0);
        }
        //获取当前时间小时
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int currentHour = calendar.get(calendar.HOUR_OF_DAY);
        //根据社工配置时间判断社工这个时段的状态
        JiajiaWorkerTimeXxConfig timeXxConfig = new JiajiaWorkerTimeXxConfig();
        timeXxConfig.setWid(worker.getId());
        timeXxConfig.setDay(DateUtils.getDate());
        List<JiajiaWorkerTimeXxConfig> timeXxConfigList = timeXxConfigService.selectTimeXxConfigList(timeXxConfig);
        if (ObjectUtil.isNotEmpty(timeXxConfigList)){
            for (JiajiaWorkerTimeXxConfig config : timeXxConfigList) {
                int star = Integer.valueOf(config.getStartime().split(":")[0]).intValue();
                int end = Integer.valueOf(config.getEndtime().split(":")[0]).intValue();
                if (star <= currentHour && currentHour < end){
                    if (config.getStatus() == 0&&star <= currentHour && currentHour < end){
                        worker.setStatus(0);
                    }
                    worker.setStatus(1);
                }
            }
        }

        resObj.put("worker",worker);
        resObj.put("workerItemList",itemList);
        resObj.put("photoList",workerPhotoList);
        resObj.put("pingJiaList",appraiseList);
        resObj.put("zuiZao", OrderUtil.getZuiZao(worker, orderList, jiedanList, detailList));

        //计算距离
        resObj.put("juLi",TokenUtil.getLuLiNum(worker.getLat(),worker.getLng())+"km");

        return AjaxResult.success(resObj);
    }

    @ApiOperation("社工评论列表")
    @PostMapping("/appraiseList")
    public AjaxResult appraiseList(@RequestParam @ApiParam(value = "社工id") Long wid){
        JiajiaAppraise appraise = new JiajiaAppraise();
        //根据社工id来查询
        appraise.setWid(wid);
        List<JiajiaAppraise> appraiseList = appraiseService.selectJiajiaAppraiseList(appraise);
        return AjaxResult.success(appraiseList);
    }

    @ApiOperation("添加评论")
    @PostMapping("/addAppraise")
    public AjaxResult addAppraise(@RequestParam @ApiParam(value = "社工id") Long wid,
                               @RequestParam @ApiParam(value = "用户id") Long uid,
                               @RequestParam @ApiParam(value = "项目id") Long iid,
                               @RequestParam @ApiParam(value = "订单id") Long oid,
                               @RequestParam @ApiParam(value = "评论内容") String content,
                               @RequestParam @ApiParam(value = "评分数") Integer score){


        JiajiaOrder order = orderService.selectJiajiaOrderById(oid);
        if (order == null)return AjaxResult.refreshAgain();

//        if(StrUtil.isEmpty(content)){
//            return AjaxResult.error("评论内容不能为空");
//        }
        if(score == null){
            return AjaxResult.error("评分不能为空");
        }

        if (order.getIsPingJia().intValue() == 1)return AjaxResult.error("已经评价过了");

        //创建对象
        JiajiaAppraise appraise = new JiajiaAppraise();
        //把要传的值添加到对象中
        appraise.setWid(wid);
        appraise.setUid(uid);
        appraise.setIid(iid);
        appraise.setOid(oid);
        appraise.setContent(content);
        appraise.setScore(score);
        appraiseService.insertJiajiaAppraise(appraise);

        order.setIsPingJia(1);
        orderService.updateJiajiaOrder(order);

        return AjaxResult.success("添加成功");
    }

    @ApiOperation("获取能举报的社工")
    @PostMapping("getCanJuBaoJiShi")
    public AjaxResult getCanJuBaoJiShi(){

        JiajiaOrder order = new JiajiaOrder();
        order.setUid(TokenUtil.getUid());
        order.setStatus(6);
        List<JiajiaOrder> orderList = orderService.selectJiajiaOrderList(order);

        JiajiaWorker worker = new JiajiaWorker();
        worker.getParams().put("idsArr",StringUtils.listsToSbStr(orderList,"wid").split(","));
        List<JiajiaWorker> workerList =workerService.selectWorkerList(worker);

        return AjaxResult.success(workerList);
    }

    @ApiOperation("获取社工相册")
    @PostMapping("/photoList")
    public AjaxResult photoList(@RequestParam @ApiParam(value = "社工id") Long wid){
        //判断客户是否登录
        JiajiaUser user =userService.selectJiajiaUserById(TokenUtil.getUid());
        if (user==null)return AjaxResult.notLogin();
        JiajiaWorkerPhoto workerPhoto=new JiajiaWorkerPhoto();
        workerPhoto.setWid(wid);
        workerPhoto.setDel(0l);
        //排序
        PageHelper.orderBy("sort desc");
        List<JiajiaWorkerPhoto> workerPhotoList = workerPhotoService.selectJiajiaWorkerPhotoList(workerPhoto);
        return AjaxResult.success(workerPhotoList);
    }

    @ApiOperation("邀请用户列表")
    @GetMapping("/inviteJiShiList")
    public AjaxResult inviteJiShiList(){
        AjaxResult ajaxResult =workerService.inviteJiShiList();
        return AjaxResult.success(ajaxResult);
    }

    @ApiOperation("邀请社工列表")
    @GetMapping("/inviteWorkerList")
    public AjaxResult inviteWorkerList(){
        AjaxResult ajaxResult =workerService.inviteWorkerList();
        return AjaxResult.success(ajaxResult);
    }

    @ApiOperation("社工与下单地址距离")
    @PostMapping("/getDistance")
    public AjaxResult getDistance(@RequestParam @ApiParam(value = "社工ID") Long workerId,
                                  @RequestParam @ApiParam(value = "纬度") String lat,
                                  @RequestParam @ApiParam(value = "经度") String lng){
        return AjaxResult.success(TokenUtil.xiaDanJuLi(lat,lng,workerId));
    }
}
